package com.venusource.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

@Slf4j
public class JwtUtil {
  /**
   * 设置有效期为 2* 60 * 60 秒
   */
  private static final Long JWT_TTL = 2 * 3600000L;
  /**
   * 设置秘钥明文
   */
  private static final String JWT_KEY = "Hello_@_World";

  private static final String ISSUER = "Hello_@_World";

  /**
   * 创建toke
   *
   * @param id
   * @param subject
   * @param ttlMillis
   * @return
   */
  public static String createJWT(String id, String subject, Long ttlMillis) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    SecretKey secretKey = generalKey();
    Date now = getNow();
    Date expDate = getExpiration(ttlMillis);
    JwtBuilder builder = Jwts.builder()
        //唯一的ID
        .setId(id)
        // 主题  可以是JSON数据
        .setSubject(subject)
        // 签发者
        .setIssuer(ISSUER)
        // 签发时间
        .setIssuedAt(now)
        //使用HS256对称加密算法签名, 第二个参数为秘钥
        .signWith(signatureAlgorithm, secretKey)
        // 设置过期时间
        .setExpiration(expDate);
    return builder.compact();
  }

  public static String createJWT(String id, String subject) {
    return createJWT(id, subject, JWT_TTL);
  }

  public static Date getNow() {
    long nowMillis = System.currentTimeMillis();
    return new Date(nowMillis);
  }

  public static Date getExpiration(Long ttlMillis) {
    long nowMillis = System.currentTimeMillis();
    if (ttlMillis == null) {
      ttlMillis = JwtUtil.JWT_TTL;
    }
    long expMillis = nowMillis + ttlMillis;
    return new Date(expMillis);
  }

  public static Date getExpiration() {
    return getExpiration(JWT_TTL);
  }

  /**
   * 解析token
   *
   * @param compactJwt
   * @return
   * @throws Exception
   */
  public static Claims parseJWT(String compactJwt) throws Exception {
    SecretKey secretKey = generalKey();
    return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(compactJwt).getBody();
  }

  /**
   * 加密
   *
   * @return
   */
  private static SecretKey generalKey() {
    byte[] encodedKey = Base64.getEncoder().encode(JwtUtil.JWT_KEY.getBytes());
    SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    return key;
  }
}
